<template>
  <div>
    <!-- 面包屑导航路径 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input placeholder="请输入内容" v-model="queryParamInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格数据 -->
      <el-table
      :data="userList"
      style="width: 100%" border stripe>
      <el-table-column
        type="index"
        label="#"
      >
      </el-table-column>
      <el-table-column
        prop="username"
        label="姓名"
      >
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
      >
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话"
      >
      </el-table-column>
      <el-table-column
        prop="role_name"
        label="角色"
      >
      </el-table-column>
      <el-table-column
        prop="mg_state"
        label="状态"
      >
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="updateUserState(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="180px"
      >
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="updateUserDialog(scope.row.id)"></el-button>
          <el-button  type="danger" size="mini" icon="el-icon-delete" @click="removeUserById(scope.row.id)"></el-button>
          <el-tooltip effect="dark" content="设置提示" placement="top-end" :enterable="false">
            <el-button  type="warning" size="mini" icon="el-icon-setting"></el-button>
          </el-tooltip>
        </template>
     </el-table-column>
    </el-table>
    <!-- 分页 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParamInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryParamInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
    title="添加用户"
    :visible.sync="addUserDialogVisible"
    width="30%"
    @close="resetAddForm"
    >
      <el-form label-width="70px" ref="addUserFormRef" :model="addUserForm" :rules="addUserFormRules">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="电话">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
    title="修改用户"
    :visible.sync="showEditDialogVisible"
    width="50%"
    @close="closeUpdateDialog"
    >
      <el-form label-width="70px" ref="editUserFormRef" :model="editUser" :rules="editUserFormRules">
        <el-form-item label="用户名">
          <el-input v-model="editUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="电话">
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, cb) => {
      // 自定义校验规则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      // 自定义校验规则
      const regMobile = /^1[3456789]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的电话'))
    }
    return {
      userList: [],
      queryParamInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      // 添加用户对话框显示状态
      addUserDialogVisible: false,
      // 修改用户对话框状态
      showEditDialogVisible: false,
      // 添加用户表单对象
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户', trigger: 'blur' },
          { min: 4, max: 8, message: '长度在 4 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改的校验规则 重复了
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 保存修改查询的用户数据
      editUser: {}
    }
  },
  methods: {
    removePath: function () {
      this.$message.success('remove acctive path')
    },
    async getUserList () {
      const { data: userData } = await this.$http.get('users', { params: this.queryParamInfo })
      if (userData.meta.status !== 200) return this.$message.error(userData.meta.msg)
      this.userList = userData.data.users
      console.log(userData)
      this.total = userData.data.total
    },
    // 分页每页大小改变
    handleSizeChange: function (newSize) {
      // console.log(newSize)
      this.queryParamInfo.pagesize = newSize
      console.log(this.queryParamInfo)
      this.getUserList()
    },
    // 分页页码改变
    handleCurrentChange: function (newNum) {
      this.queryParamInfo.pagenum = newNum
      this.getUserList()
    },
    // 修改用户状态
    async updateUserState (user) {
      const { data: res } = await this.$http.put('/users/' + user.id + '/state/' + user.mg_state)
      if (res.meta.status !== 200) {
        user.msg = !user.msg
        return this.$message.error('修改用户状态失败')
      }
      this.$message.success('修改用户状态成功')
    },
    // 关闭对话框之前的事件
    // handleClose: function () {

    // }
    // open add user dailog
    // addUserDialog: function () {
    //   this.addUserDialogVisible = true
    // }
    // 关闭添加对话框 重置添加表单
    resetAddForm: function () {
      this.$refs.addUserFormRef.resetFields()
    },
    addUser: function () {
      this.$refs.addUserFormRef.validate(async validate => {
        if (!validate) return this.$message.error('验证未通过')
        const { data: res } = await this.$http.post('users', this.addUserForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addUserDialogVisible = false
        this.getUserList()
      })
    },
    // 打开修改框
    async updateUserDialog (userId) {
      console.log(userId)
      const { data: res } = await this.$http.get('users/' + userId)
      console.log(res)
      this.editUser = res.data
      this.showEditDialogVisible = true
      if (res.meta.status !== 200) return this.$message.error('获取用户数据失败')
    },
    // 修改用户数据
    updateUser: function () {
      this.$refs.editUserFormRef.validate(async validate => {
        if (!validate) return this.$message.error('参数验证不通过')
        const { data: res } = await this.$http.put('users/' + this.editUser.id, { email: this.editUser.email, mobile: this.editUser.mobile })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.showEditDialogVisible = false
        this.getUserList()
        this.$message.success('修改数据成功')
      })
    },
    // 防止后台没有数据 触发blur 验证提示 关闭时关闭验证提示
    closeUpdateDialog: function () {
      this.$refs.editUserFormRef.resetFields()
    },
    // removeUserById
    async removeUserById (id) {
      console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      if (confirmResult !== 'confirm') return this.$message.info('已经取消删除用户')
      const { data: res } = await this.$http.delete('users' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除成功')
    }

  },
  created () {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>

</style>
